package cn.itcast.bos.service.base.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.bos.dao.base.ICourierRepository;
import cn.itcast.bos.dao.base.IFixedAreaRepository;
import cn.itcast.bos.dao.base.ITakeTimeRepository;
import cn.itcast.bos.domain.base.Courier;
import cn.itcast.bos.domain.base.FixedArea;
import cn.itcast.bos.domain.base.TakeTime;
import cn.itcast.bos.service.base.IFixedAreaService;

@Service
@Transactional
public class FixedAreaServiceImpl implements IFixedAreaService {
    // 注入reporsitory
    @Autowired
    private IFixedAreaRepository fixedAreaRepository;

    // 添加定区
    @Override
    public void saveFixedArea(FixedArea fixedArea) {
        fixedAreaRepository.save(fixedArea);
    }

    // 有条件分页查询
    @Override
    public Page<FixedArea> pageQueryFixedArea(Specification<FixedArea> specification, Pageable pageable) {
        // TODO Auto-generated method stub
        return fixedAreaRepository.findAll(specification, pageable);
    }

    // 关联快递员
    @Autowired
    private ITakeTimeRepository takeTimeRepository;
    @Autowired
    private ICourierRepository courierRepository;

    @Override
    public void associationCourierToFixedArea(FixedArea fixedArea, Integer takeTimeId, Integer courierId) {
        // 将瞬时台转为持久态
        FixedArea persistFixedArea = fixedAreaRepository.findOne(fixedArea.getId());
        TakeTime persistTakeTime = takeTimeRepository.findOne(takeTimeId);
        Courier persistCourier = courierRepository.findOne(courierId);
        // 将快递员关联到定区上
        persistFixedArea.getCouriers().add(persistCourier);
        // 将快递员与收派标准关联
        persistCourier.setTakeTime(persistTakeTime);
    }

}
